package com.distribute.framework.core.util;

import java.lang.reflect.Field;

public class Reflect {
	
	
	String string="我了个去";
	Reflect reflect = null;

	
	public static Field getField(Object object,String name){
		Field field = null;
		try {
			field = object.getClass().getDeclaredField(name);
		} catch (Exception e) {
			e.printStackTrace();
		}
		field.setAccessible(true);
		return field;
	}
	
	public static Object get(Object object,String name){
		Object targetObject = object;
		String[] array = name.split("\\.");
		for(String key:array){			
			try {
				targetObject = getField(targetObject,key).get(targetObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return targetObject;
	}
	
	public static Object set(Object object,String name,Object value){		
		Object targetObject = object;
		String[] array = name.split("\\.");
		for(int i=0;i<array.length-2;i++){
			String key=array[i];
			try {
				targetObject = getField(targetObject,key).get(targetObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			getField(targetObject,array[array.length-1]).set(targetObject, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return targetObject;
	}
	
	public static void main(String...strings){
		Reflect eee = new Reflect();
		System.out.println(Reflect.get(eee, "string"));
		Reflect.set(eee, "reflect", eee);
		System.out.println(Reflect.get(eee, "reflect.reflect.string"));
		Reflect.set(eee, "reflect.reflect.string", "霏霏");
		System.out.println(Reflect.get(eee, "reflect.reflect.string"));
		System.out.println(Reflect.get(eee, "string"));
	}
	
	
}